package MySQL;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.storage.MainActivity;
import com.example.storage.R;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Login extends AppCompatActivity {
    private TextView registerTab, signInTab;
    private Button continueButton, loginButton;
    private EditText username, email, phoneOrEmail, password, phone, register_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isUserLoggedIn()) {
            // 用户已经登录，直接跳转到MainActivity
            Intent intent = new Intent(Login.this, MainActivity.class);
            startActivity(intent);
            finish(); // 结束当前活动
            return;
        }

        setContentView(R.layout.activity_register);
        initializeRegisterView();
    }

    //在LoginActivity启动时，检查SharedPreferences中的登录状态。
    private boolean isUserLoggedIn() {
        SharedPreferences sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        return sharedPreferences.getBoolean("isLoggedIn", false);
    }

//使用SharedPreferences保存登录状态和用户信息
    private void saveLoginState(boolean isLoggedIn, String username, String phone, String email) {
        SharedPreferences sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
        editor.putString("username", username);
        editor.putString("phone", phone);
        editor.putString("email", email);
        editor.apply();
    }

    private void initializeLoginView() {
        registerTab = findViewById(R.id.register_tab);
        signInTab = findViewById(R.id.sign_in_tab);
        loginButton = findViewById(R.id.login_button);
        phoneOrEmail = findViewById(R.id.username_or_email);
        password = findViewById(R.id.password);

        registerTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setContentView(R.layout.activity_register);
                initializeRegisterView();
            }
        });


//        登录界面处理逻辑
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection con = jdbcHelper.getCon();
                        String sqlStr = "SELECT * FROM userinfo WHERE (email=? OR phone=?) AND psw=?";
                        try {
                            PreparedStatement ps = (PreparedStatement) con.prepareStatement(sqlStr);
                            ps.setString(1, phoneOrEmail.getText().toString());
                            ps.setString(2, phoneOrEmail.getText().toString());
                            ps.setString(3, password.getText().toString());
                            ResultSet rs = ps.executeQuery();
                            Looper.prepare();
                            if (rs.next()) {
                                String username = rs.getString("uname");
                                String phone = rs.getString("phone");
                                String email = rs.getString("email");
                                saveLoginState(true, username, phone, email);
                                runOnUiThread(() -> {
                                    Toast.makeText(Login.this, "登录成功", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(Login.this, MainActivity.class);
                                    startActivity(intent);
                                    finish(); // 结束当前活动
                                });
                            } else {
                                runOnUiThread(() -> Toast.makeText(Login.this, "登录失败", Toast.LENGTH_SHORT).show());
                            }
                            Looper.loop();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        TextWatcher loginTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要实现
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkLoginFieldsForEmptyValues();
            }
        };

        phoneOrEmail.addTextChangedListener(loginTextWatcher);
        password.addTextChangedListener(loginTextWatcher);
    }

    private void checkLoginFieldsForEmptyValues() {
        String phoneOrEmailText = phoneOrEmail.getText().toString();
        String passwordText = password.getText().toString();

        if (!phoneOrEmailText.isEmpty() && !passwordText.isEmpty()) {
            loginButton.setBackgroundColor(Color.BLUE);
        } else {
            loginButton.setBackgroundColor(Color.GRAY);
        }
    }

//    注册界面处理逻辑
    private void initializeRegisterView() {
        registerTab = findViewById(R.id.register_tab);
        signInTab = findViewById(R.id.sign_in_tab);
        continueButton = findViewById(R.id.continue_button);
        username = findViewById(R.id.username);
        email = findViewById(R.id.email);
        phone = findViewById(R.id.phone);
        register_password = findViewById(R.id.register_passward);

        signInTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setContentView(R.layout.activity_login);
                initializeLoginView();
            }
        });

        continueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Connection con = jdbcHelper.getCon();
                        String sqlStr = "select * from userinfo where uname=?";
                        try {
                            PreparedStatement ps = (PreparedStatement) con.prepareStatement(sqlStr);
                            ps.setString(1, username.getText().toString());
                            ResultSet rs = ps.executeQuery();
                            Looper.prepare();
                            if (rs.next()) {
                                runOnUiThread(() -> Toast.makeText(Login.this, "用户名已存在", Toast.LENGTH_SHORT).show());
                            } else {
                                String sqlStr1 = "insert into userinfo(uname,psw,email,phone) values(?,?,?,?)";
                                try {
                                    PreparedStatement ps1 = (PreparedStatement) con.prepareStatement(sqlStr1);
                                    ps1.setString(1, username.getText().toString());
                                    ps1.setString(2, register_password.getText().toString());
                                    ps1.setString(3, email.getText().toString());
                                    ps1.setString(4, phone.getText().toString());
                                    int rows = ps1.executeUpdate();
                                    if (rows > 0) {
                                        runOnUiThread(() -> {
                                            Toast.makeText(Login.this, "注册成功", Toast.LENGTH_SHORT).show();
                                            setContentView(R.layout.activity_login);
                                            initializeLoginView();
                                        });
                                    }
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }
                            Looper.loop();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        TextWatcher registerTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要实现
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkRegisterFieldsForEmptyValues();
            }
        };

        username.addTextChangedListener(registerTextWatcher);
        email.addTextChangedListener(registerTextWatcher);
        phone.addTextChangedListener(registerTextWatcher);
        register_password.addTextChangedListener(registerTextWatcher);
    }

    private void checkRegisterFieldsForEmptyValues() {
        String usernameText = username.getText().toString();
        String emailText = email.getText().toString();
        String phoneText = phone.getText().toString();
        String passwordText = register_password.getText().toString();

        boolean isUsernameValid = !usernameText.isEmpty();
        boolean isEmailValid = !emailText.isEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailText).matches();
        boolean isPhoneValid = !phoneText.isEmpty() && Patterns.PHONE.matcher(phoneText).matches();
        boolean isPasswordValid = !passwordText.isEmpty();

        if (isUsernameValid && isEmailValid && isPhoneValid && isPasswordValid) {
            continueButton.setBackgroundColor(Color.BLUE);
            continueButton.setEnabled(true);
        } else {
            continueButton.setBackgroundColor(Color.GRAY);
            continueButton.setEnabled(false);
        }
    }
}
